package com.ruoyi.internet.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: cjie
 * @description: 短信发送
 * @date: 2021/8/17
 */
@Component
public class SendMsgUtil {
    private final static long EXPIRE_TIME = 5;

    @Value("${alisms.accessKeyId}")
    private String accessKeyId;
    @Value("${alisms.accessSecret}")
    private String accessSecret;
    @Value("${alisms.signName}")
    private String signName;
    @Value("${alisms.templateCode}")
    private String templateCode;

    @Autowired
    private RedisService redisService;

    private static final Logger logger = LoggerFactory.getLogger(SendMsgUtil.class);

    public AjaxResult sendMsg(String phone) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        //生成6位数验证码
        String checkCode = RandomStringUtils.randomNumeric(6);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",checkCode);
        request.putQueryParameter("TemplateParam",jsonObject.toJSONString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            //{"RequestId":"7B74C3A5-8B2D-50E9-9D26-DD4D58797518","Message":"OK","BizId":"894506830136810969^0","Code":"OK"}
            if ("OK".equals(JSON.parseObject(response.getData()).getString("Code"))) {
                redisService.setCacheObject(phone, checkCode, EXPIRE_TIME, TimeUnit.MINUTES);
                return AjaxResult.success();
            }
        } catch (ClientException e) {
            logger.error("发送短信错误", e.getLocalizedMessage());
        }

        return AjaxResult.error();
    }
}

